package com.javachmapi.controller;

import cn.hutool.json.JSONObject;
import com.javachmapi.entity.User;
import com.javachmapi.entity.UserToken;
import com.javachmapi.service.UserService;
import com.javachmapi.service.UserTokenService;
import com.javachmapi.vo.ResponseData;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 用户表(User)表控制层
 *
 * @author 宋利军
 * @since 2020-11-09 01:26:30
 */
@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;
    @Resource
    private UserTokenService userTokenService;

    @GetMapping("/register")
    public ResponseData register(@RequestParam(name = "nickname") String nickname,
                                 @RequestParam(name = "username") String username,
                                 @RequestParam(name = "password") String password,
                                 @RequestParam(name = "address") String address){

        User user = new User();
        user.setUsername(username);
        user.setPassword(DigestUtils.md5Hex(password));
        user.setNickname(nickname);
        user.setAddress(address);
        user.setStatus(0);
        user.setCtime(new Date());
        userService.insert(user);
        return ResponseData.success("注册成功！");
    }

    /**
     * 登陆账号密码
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/login")
    public ResponseData login(@RequestParam(name = "username") String username,
                              @RequestParam(name = "password") String password){
        User user = userService.findByUserNameAndPassword(username);
        if (!user.getPassword().equals(DigestUtils.md5Hex(password))) {
            return ResponseData.failure("账号或密码不正确！");
        }
        if (user.getStatus()==0){
            return ResponseData.failure("账号未激活！");
        }else if(user.getStatus()==2){
            return ResponseData.failure("账号已被锁定！");
        }
        //开始创建token
        //获取token
        UserToken token = userTokenService.check(user);
        //登录成功
        JSONObject data = new JSONObject();
        data.put("token", token.getToken());
        data.put("expireTime", token.getExpiretime());
        data.put("user", user);
        return ResponseData.success("登陆成功!",data);
    }

}